<%--
  Created by IntelliJ IDEA.
  User: Reimu
  Date: 2022/5/7
  Time: 12:56
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>guess</title>
</head>
<body>


<%
    int target = (int) session.getAttribute("target");
    int count = (int) session.getAttribute("count");

    String message = "";
    try {
        // 获取用户猜的数字
        int num = Integer.parseInt(request.getParameter("num"));
        // 猜测次数累加1
        count++;
        // 将用户猜的数字与猜测目标随机整数进行比较
        if (num > target) {
            // 将猜测次数写入session
            session.setAttribute("count", count);
            // 设置提示信息
            if (count > 1) {
                message = "Good guess, but nope. Try <b>lower</b>. You have made " + count + " guesses.";
                out.println(message);
            } else {
                message = "Good guess, but nope. Try <b>lower</b>. You have made " + count + " guess.";
                out.println(message);
            }
        } else if (num < target) {
            // 将猜测次数写入session
            session.setAttribute("count", count);
            // 设置提示信息
            if (count > 1) {
                message = "Good guess, but nope. Try <b>higher</b>. You have made " + count + " guesses.";
                out.println(message);
            } else {
                message = "Good guess, but nope. Try <b>higher</b>. You have made " + count + " guess.";
                out.println(message);
            }
        } else {
            // 设置提示信息
            message = "Congratulations! You got it. And after just " + count + " tries.<br/>" +
                    "Care to <a href='numguess.jsp'>try again</a>?";
            out.println(message);
            // 删除session里的猜测目标与猜测次数
            session.removeAttribute("target");
            session.removeAttribute("count");
        }
    } catch (NumberFormatException e) {
        System.err.println(e.getMessage());
    }
%>


</body>
</html>
